<script lang="ts" setup>
import { ref, computed } from 'vue'
import {
  NSpace,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NCheckbox,
  NScrollbar,
  NInputNumber,
  NCard,
  FormInst,
  FormItemRule,
  FormRules
} from 'naive-ui'
import { GlobeOutline } from '@vicons/ionicons5'
import SeniorRadioGroup from '@/components/senior-radio-group.vue'
import SeniorRadio from '@/components/senior-radio.vue'

const emit = defineEmits(['nextStep', 'prevStep'])

const segmentationValue = ref(1)
const indexingValue = ref(1)
const formRef = ref<FormInst | null>(null)

const customSettings = ref({
  segmentIdentifier: '\\n\\n',
  maxSegmentLength: 500,
  overlapLength: 50,
  preprocessingRules: []
})

const previewSegments = ref([
  { id: '001', content: '公共事项', wordCount: 4 },
  { id: '002', content: '运营问题', wordCount: 4 },
  { id: '003', content: '运营问题|责任人|时间|说明|', wordCount: 24 },
  { id: '004', content: '---|---|---|---|', wordCount: 25 },
  { id: '005', content: '|||||', wordCount: 9 }
])

const rules: FormRules = {
  segmentIdentifier: [
    { required: true, message: '请输入分段标识符号', trigger: ['blur', 'input'] }
  ],
  maxSegmentLength: [
    {
      required: true,
      type: 'number',
      min: 1,
      message: '请输入有效的最大分段长度',
      trigger: ['blur', 'input']
    }
  ],
  overlapLength: [
    {
      required: true,
      type: 'number',
      min: 0,
      message: '请输入有效的分段重叠长度',
      trigger: ['blur', 'input']
    }
  ]
}

const handleNextStep = () => {
  if (segmentationValue.value === 2) {
    formRef.value?.validate((errors) => {
      if (!errors) {
        emit('nextStep')
      }
    })
  } else {
    emit('nextStep')
  }
}

const handlePrevStep = () => {
  emit('prevStep')
}

const previewSettings = () => {
  if (segmentationValue.value === 2) {
    formRef.value?.validate((errors) => {
      if (!errors) {
        console.log('Preview settings:', customSettings.value)
        // Implement preview logic here and update previewSegments
      }
    })
  } else {
    console.log('Preview settings:', customSettings.value)
    // Implement preview logic here and update previewSegments
  }
}

const resetSettings = () => {
  customSettings.value = {
    segmentIdentifier: '\\n\\n',
    maxSegmentLength: 500,
    overlapLength: 50,
    preprocessingRules: []
  }
}

const togglePreprocessingRule = (value: number) => {
  const index = customSettings.value.preprocessingRules.indexOf(value)
  if (index === -1) {
    customSettings.value.preprocessingRules.push(value)
  } else {
    customSettings.value.preprocessingRules.splice(index, 1)
  }
}

const isFormValid = computed(() => {
  if (segmentationValue.value === 1) return true
  return (
    !!customSettings.value.segmentIdentifier &&
    !!customSettings.value.maxSegmentLength &&
    !!customSettings.value.overlapLength
  )
})
</script>

<template>
  <p class="text-3xl mb-8">文本分段与清洗</p>
  <div class="flex gap-8 justify-between">
    <NScrollbar content-style="height: calc(100vh - 350px); width: 100%" class="max-w-3xl">
      <n-space vertical>
        <p class="text-2xl">分段设置</p>
        <senior-radio-group v-model:value="segmentationValue" class="w-full">
          <senior-radio
            :value="1"
            :icon="GlobeOutline"
            iconColor="#7839EE"
            iconBackgroundColor="#F5F3FF"
            label="自动分段与清洗"
            description="自动设置分段规则与预处理规则，如果不了解这些参数建议选择此项"
          >
          </senior-radio>
          <senior-radio
            :value="2"
            :icon="GlobeOutline"
            iconColor="#528bff"
            iconBackgroundColor="rgba(82, 139, 255, 0.1)"
            label="自定义"
            description="自定义分段规则、分段长度以及预处理规则等参数"
          >
            <n-form ref="formRef" :model="customSettings" :rules="rules" class="px-50px mt-10px">
              <n-form-item label="分段标识符号" path="segmentIdentifier">
                <n-input v-model:value="customSettings.segmentIdentifier" />
              </n-form-item>
              <n-form-item label="最大分段长度" path="maxSegmentLength">
                <n-input-number class="w-full" v-model:value="customSettings.maxSegmentLength" />
              </n-form-item>
              <n-form-item label="分段重叠长度" path="overlapLength">
                <n-input-number class="w-full" v-model:value="customSettings.overlapLength" />
              </n-form-item>
              <n-form-item label="文本预处理规则" path="preprocessingRules">
                <n-space vertical>
                  <n-checkbox
                    :checked="customSettings.preprocessingRules.includes(1)"
                    @update:checked="togglePreprocessingRule(1)"
                    label="替换掉连续的空格、换行符和制表符"
                  />
                  <n-checkbox
                    :checked="customSettings.preprocessingRules.includes(2)"
                    @update:checked="togglePreprocessingRule(2)"
                    label="删除所有 URL 和电子邮件地址"
                  />
                </n-space>
              </n-form-item>
              <div class="flex mt-10px w-full gap-5">
                <n-button class="rounded-xl w-100px" @click="resetSettings">重置参数</n-button>
                <n-button type="primary" class="rounded-xl w-100px" @click="previewSettings"
                  >立即预览</n-button
                >
              </div>
            </n-form>
          </senior-radio>
        </senior-radio-group>
        <p class="text-2xl">索引方式</p>
        <senior-radio-group v-model:value="indexingValue" class="w-full">
          <div class="w-full flex gap-10px">
            <senior-radio
              :value="1"
              :icon="GlobeOutline"
              iconColor="#7839EE"
              iconBackgroundColor="#F5F3FF"
              label="高质量"
              description="调用系统默认的嵌入接口进行处理，以在用户查询时提供更高的准确度"
            >
              <div class="pl-50px w-full mt-10px flex flex-col">
                <span>执行预估消耗</span>
                <span>66.00 tokens (<span class="text-yellow-500">$0.000000008</span>)</span>
              </div>
            </senior-radio>
            <senior-radio
              :value="2"
              :icon="GlobeOutline"
              iconColor="#528bff"
              iconBackgroundColor="rgba(82, 139, 255, 0.1)"
              label="经济"
              description="使用离线的向量引擎、关键词索引等方式，降低了准确度但无需花费 Token"
            >
            </senior-radio>
          </div>
        </senior-radio-group>
      </n-space>
    </NScrollbar>

    <!-- 新增的预览分段列表 -->
    <NCard title="分段预览" class="flex w-600px rounded-xl">
      <NScrollbar style="height: calc(100vh - 350px)">
        <n-space vertical>
          <div
            v-for="segment in previewSegments"
            :key="segment.id"
            class="border-1px mb-10px border-gray-100 border-solid border-1 p-10px bg-gray-50 rounded-xl"
          >
            <div class="flex justify-between items-center">
              <n-tag size="small" round>{{ segment.id }}</n-tag>
              <span class="text-sm text-gray-500">{{ segment.wordCount }} 字符</span>
            </div>
            <p class="mt-1">{{ segment.content }}</p>
          </div>
        </n-space>
      </NScrollbar>
    </NCard>
  </div>
  <div class="flex w-full gap-5 mt-4">
    <n-button class="rounded-xl" @click="handlePrevStep">上一步</n-button>
    <n-button type="primary" class="rounded-xl" @click="handleNextStep" :disabled="!isFormValid"
      >保存并处理</n-button
    >
  </div>
</template>

<style scoped>
/* 可以根据需要添加额外的样式 */
</style>
